package com.xiamo.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiamo.common.AjaxResult;
import com.xiamo.entity.DwKeyLog;
import com.xiamo.enums.AllStatusEnum;
import com.xiamo.service.IDwKeyLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.sql.Wrapper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:  卡密领取日志
 * @return:
 * @Author: dawu
 * @Date: 2024-04-09 10:02
 */
@RestController
@RequestMapping("key")
public class DwKeyLogController {

    @Autowired
    private IDwKeyLogService dwKeyLogService;

    private static final String ROOT_PATH = System.getProperty("user.dir");
    private RestTemplate restTemplate = new RestTemplate();


    @GetMapping("list")
    public AjaxResult list(DwKeyLog dwKeyLog){

        List<DwKeyLog> logList =dwKeyLogService.list(Wrappers.<DwKeyLog>lambdaQuery()
                .eq(DwKeyLog::getUserId,dwKeyLog.getUserId())
                .orderByDesc(DwKeyLog::getCreateTime));
        return AjaxResult.success(logList);
    }

    @PostMapping("save")
    public AjaxResult save(HttpServletRequest request, @RequestBody DwKeyLog dto) throws ParseException {
        String clientIP = getClientIP(request);

        Date date = new Date();

        dto.setCreateTime(date);
        dto.setStatus(AllStatusEnum.SUCCESS.getValue());

        //查看该用户领取的key需要 > 24h 才能再次领取
        DwKeyLog dwKeyLog = dwKeyLogService.getOne(Wrappers.<DwKeyLog>lambdaQuery()
                .eq(DwKeyLog::getUserId,dto.getUserId())
                .eq(DwKeyLog::getType,dto.getType())
                .orderByDesc(DwKeyLog::getCreateTime)
                .last("limit 1"));


        dto.setKeyStr(getRandomKey(dto.getType()));//getRandomKey(dto.getType())
        if(null!= dwKeyLog){
            long timeDiff = date.getTime() - dwKeyLog.getCreateTime().getTime();
            long hoursDiff = timeDiff / (1000 * 60 * 60); // 将毫秒转换为小时
            if (hoursDiff >= 12) {
                dwKeyLogService.save(dto);
                return AjaxResult.success(dto);
            } else {
                long remainingHours = 12 - hoursDiff;
                return AjaxResult.error("还需等待 " + remainingHours + " 小时才能再次领取");
            }

        }
        dwKeyLogService.save(dto);
        sendPushNotification( dto, clientIP);
        return AjaxResult.success(dto);
    }
    public String getRandomKey(Integer type) {
        // 从txt文件中读取卡密列表
        List<String> keyList = readKeyListFromFile(type);

        // 随机获取一个卡密
        Random random = new Random();
        int randomIndex = random.nextInt(keyList.size());
        return keyList.get(randomIndex);
    }

    public List<String> readKeyListFromFile(Integer type) {
        List<String> keyList = new ArrayList<>();

        try {
            // 读取txt文件
            File file = new File(ROOT_PATH + "/file/file.txt");
            if(type ==1) {
                 file = new File(ROOT_PATH + "/file/file.txt");
            }else {
                file = new File(ROOT_PATH + "/file/password.txt");
            }
            BufferedReader reader = new BufferedReader(new FileReader(file));

            String line;
            while ((line = reader.readLine()) != null) {
                keyList.add(line);
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return keyList;
    }

    private void sendPushNotification(DwKeyLog dto,String clientIP) {

        String cityInfo = getCityInfo(clientIP); // 根据IP地址获取城市信息

        String content = "IP" + clientIP + " - City" + cityInfo;

        // 使用axios发送HTTP GET请求调用推送接口
        String url = "http://www.pushplus.plus/send";
        String token = "f1803fa4facd437e8e018b827453311a";
        String title = dto.getType()==1?"小程序 用户获取uuid":"小程序 用户获取DWai密码";
        String template = "html";

        try {
            // 构建URL参数

            String requestUrl = url + "?token=" + token + "&title=" + title + "&content=" + content + "&template=" + template;

            // 发送HTTP GET请求
            ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class);

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK) {
                // 推送成功
                System.out.println("推送通知成功");
            } else {
                // 推送失败
                System.out.println("推送通知失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            System.out.println("推送通知失败：" + e.getMessage());
        }
    }

    private String getClientIP(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                // 获取本地真实IP地址
                InetAddress inetAddress;
                try {
                    inetAddress = InetAddress.getLocalHost();
                    ipAddress = inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        // 多个代理服务器情况下，第一个非unknown的IP地址为真实IP地址
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }



    private String getCityInfo(String clientIP) {
        String apiUrl = "http://api.vore.top/api/IPdata";
        String requestUrl = apiUrl + "?ip=" + clientIP;

        try {
            // 发送HTTP GET请求
            ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class);

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK) {
                String responseData = response.getBody();

                // 解析响应数据
                JSONObject jsonObject = new JSONObject(responseData);

                String info1 = jsonObject.getJSONObject("adcode").getStr("o");


                return info1;
            } else {
                // 请求失败
                System.out.println("获取城市信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            System.out.println("获取城市信息失败：" + e.getMessage());
        }

        return "Unknown";
    }

}
